package org.altervista.cp.thinjdbc.wrappers;

import java.util.LinkedList;

import org.altervista.cp.thinbcgen.proxy.ProxyGenerator;
import org.altervista.cp.thinbcgen.proxy.UpdatableProxy;

public class WrapperCache<T, E> {

	public WrapperCache(ProxyGenerator proxyGen) {
		_proxyGen = proxyGen;
	}

	@SuppressWarnings("unchecked")
	public T get(E o) {
		synchronized (_cacheList) {
			T proxy = null;
			if (_cacheList.isEmpty()) {
				proxy = (T) _proxyGen.generate(o);
			} else {
				proxy = _cacheList.removeLast();
			}
			((UpdatableProxy) proxy).proxy(o);
			return proxy;
		}
	}

	public void dispose(T o) {
		synchronized (_cacheList) {
			((UpdatableProxy) o).proxy(null);
			_cacheList.addFirst(o);
		}
	}

	private LinkedList<T> _cacheList = new LinkedList<T>();
	private ProxyGenerator _proxyGen;
}
